package com.thot.timyag.config.datasource;

import javax.sql.DataSource;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;

import com.thot.timyag.config.properties.DatasourceProperties;
import com.thot.timyag.config.properties.PersistenceProperties;
import com.thot.timyag.exceptions.ThotException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * @author yangjf
 * @time 2019-06-25 15:11
 */


public class DatasourceSington {
    private static DataSource dataSource;
    public static PersistenceProperties persistenceProperties;

    public static DataSource getDataSource() {
        if (dataSource == null) {
            init();
        }
        return dataSource;
    }

    public static void setPersistenceProperties(PersistenceProperties pproperties) {
        persistenceProperties = pproperties;
    }


    private static void init() {
        if (persistenceProperties.isEnable()) {
            //持久化数据
            DatasourceProperties config = persistenceProperties.getDatasource();
            DriverManagerDataSource driverDataSource = new DriverManagerDataSource(config.getUrl(), config.getUsername(), config.getPassword());
            driverDataSource.setDriverClassName(config.getDriverClassName());

            //执行初始化脚本
            try (Reader reader = Resources.getResourceAsReader("sql/schema.sql")) {
                ScriptRunner runner = new ScriptRunner(driverDataSource.getConnection());
                runner.setAutoCommit(true);
                runner.setStopOnError(false);
                runner.setLogWriter(null);
                runner.setErrorLogWriter(null);
                runner.runScript(reader);
            } catch (IOException e) {
                throw new ThotException("初始化数据库失败");
            } catch (SQLException e) {
                throw new ThotException("数据库连接失败");
            }
            dataSource = driverDataSource;
        }
    }

}
